import ProposalAPI from '@/api/Proposal';
import { useCall, useQueryValue, useReq, useSimpleMemo } from '@/components';
import { createContext, useContext, useEffect, useState } from 'react';

const DefinitionContext = createContext({ definitionData: null, setData() {} });

export default DefinitionContext;

export function useDefinitionData() {
  return useContext(DefinitionContext)?.definitionData ?? null;
}

export function useUpdateDefinition() {
  const context = useContext(DefinitionContext);
  return useCall((data) => context?.setData(data));
}

export function useProductCode() {
  return useDefinitionData()?.productDefineList?.[0]?.productCode ?? null;
}

export function useCombinationType() {
  return useDefinitionData()?.productDefineList?.[0]?.combinationType ?? null;
}

export function useDefinitionContext() {
  const definitionId = useQueryValue('code');
  const [data, setData] = useState(null);
  const xhr = useReq(ProposalAPI.byId);

  useEffect(() => {
    if (data !== xhr.result) setData(xhr.result?.data ?? null);
  }, [xhr.result]);

  const refresh = useCall(() => (definitionId ? xhr.start(definitionId) : false));
  useEffect(() => {
    refresh();
  }, [definitionId]);

  return useSimpleMemo([data ?? null, setData, xhr.status === 'loading', refresh]);
}
